directives.directive('fileUp', ["$rootScope", "tools", "$timeout","$compile", function ($rootScope, tools, $timeout,$compile) {
    return {
        restrict: 'AE',
        scope: {},
        replace: true,
        templateUrl: "/trend-new-BI/app/components/dbManager/fileUp/fileUpView.html",
        link: function (scope, element, attr) {
            $(element).height(document.documentElement.clientHeight * 0.88);

            $rootScope.$on("showMySheet_EV", function (e,data) {
              //  console.log("AA");

                if(data=="look"){
                 //   console.log("BB");
                    $(element).modal("show");
                    $rootScope.$broadcast("loading_Start_EV");
                    $timeout(function(){
                        $rootScope.$broadcast("loading_End_EV");
                    },500);
                }else{
                   // console.log("CC");
                    $timeout(function () {
                        $(element).modal("show");
                        $rootScope.$broadcast("loading_Start_EV");
                    }, 100);
                }

            });
            $rootScope.$on("DataIsApeendED",function(e,data){
               // console.log("loading");
                $timeout(function(){
                    $rootScope.$broadcast("loading_End_EV");
                    scope.myTimer = true;
                },800);
            });

            function appendToTable(resp) {
                scope.mycaptionSelectNum = -1;
                scope.headsAtLineIndex[scope.sheetF.sheetIndex] = -1;
              //  console.log("scope.headsAtLineIndex");
              //  console.log(scope.headsAtLineIndex);
                //sheet1 dataTypes
                scope.sheetDataTypes[scope.sheetF.sheetIndex] = resp.excel.dataTypes;
                //sheet表的首个字段数据
                scope.sheetHeads[scope.sheetF.sheetIndex] = resp.excel.heads;


               // console.log("sheetDataType:");
              //  console.log(scope.sheetDataTypes[0]);

                //初始数据类型的默认值
                var dataTypes = [];

                var hideOneTds = false;
                //scope.isHideThisTd[scope.sheetF.sheetIndex]=[];
              //  console.log("scope.isHideThisTd");
               // console.log(scope.isHideThisTd);
                scope.isHideThisTd[scope.sheetF.sheetIndex] = [];
                angular.forEach(resp.excel.dataTypes, function (item, index) {

//                    scope.isHideThisTd[scope.sheetF.sheetIndex].push({show: true});

                    dataTypes.push({show: true});
                    //console.log(item);
                    //空对象
                    if ($.isEmptyObject(item)) {
                        console.log("item");
                        dataTypes[index].show = false;
                    }


                    for (var key in item) {
                       // console.log("key: "+key +"  value:"+item[key]);
                        dataTypes[index].type = item[key];
                        dataTypes[index].str = key;

                        //dataTypes.push({type:item[i],str:i});
                        //return;
                    }
                });
                scope.isHideThisTd[scope.sheetF.sheetIndex] = dataTypes;
               // console.log(scope.isHideThisTd[scope.sheetF.sheetIndex]);



                //dataType put
                scope.sheetDataType[scope.sheetF.sheetIndex] = angular.copy(dataTypes);//存放数字

                //对行号的处理--100-100
                var MaxlineNum = resp.excel.lineNum;
                var descIndex = MaxlineNum - 100;


//表格tds数据
                var tdsHTML = "";
                scope.lineNum[scope.sheetF.sheetIndex] = [];

                angular.forEach(resp.excel.datas, function (item, index) {
//            console.log(item);
                    if (MaxlineNum < 199) {
                        tdsHTML += '<tr ng-class="{throline:mycaptionSelectNum>'+index+'}" ng-dblclick="mycaptionS(' + index + ')" index="' + (index + 1) + '">';
                        tdsHTML += '<td class="fisrt"><div><span ng-show="headsAtLineIndex[sheetF.sheetIndex]==' + index + '">双击选择该标题行</span><div ng-hide="headsAtLineIndex[sheetF.sheetIndex]==' + index + '" class="ui fitted slider checkbox"><input index="' + (index + 1) + '" type="checkbox"> <label></label></div></div></td>';
                        angular.forEach(item, function (item2,tdIndex) {

                            tdsHTML += '<td title="'+item2+'" ng-show="isHideThisTd[sheetF.sheetIndex]['+tdIndex+'].show">' + item2 + '</td>';
                        });
                        tdsHTML += '</tr>';
                        scope.lineNum[scope.sheetF.sheetIndex].push({line: index + 1, show: false});
                    } else {
                        if (index <= 99) {
                            tdsHTML += '<tr  ng-class="{throline:mycaptionSelectNum>'+index+'}" ng-dblclick="mycaptionS(' + index + ')" index="' + (index + 1) + '">';
                            tdsHTML += '<td class="fisrt"><div><span ng-show="headsAtLineIndex[sheetF.sheetIndex]==' + index + '">双击选择该标题行</span><div ng-hide="headsAtLineIndex[sheetF.sheetIndex]==' + index + '" class="ui fitted slider checkbox"><input index="' + (index + 1) + '" type="checkbox"> <label></label></div></div></td>';
                            angular.forEach(item, function (item2,tdIndex) {
                                tdsHTML += '<td title="'+item2+'" ng-show="isHideThisTd[sheetF.sheetIndex]['+tdIndex+'].show">' + item2 + '</td>';
                            });
                            tdsHTML += '</tr>';
                            scope.lineNum[scope.sheetF.sheetIndex].push({line: index + 1, show: false});
                        } else {

                            tdsHTML += '<tr  ng-class="{throline:mycaptionSelectNum>'+index+'}" ng-dblclick="mycaptionS(' + index + ')" index="' + descIndex + '">';
                            tdsHTML += '<td class="fisrt"><div><span ng-show="headsAtLineIndex[sheetF.sheetIndex]==' + index + '">双击选择该标题行</span><div ng-hide="headsAtLineIndex[sheetF.sheetIndex]==' + index + '" class="ui fitted slider checkbox"><input index="' + (index + 1) + '" type="checkbox"> <label></label></div></div></td>';
                            angular.forEach(item, function (item2,tdIndex) {
                                tdsHTML += '<td title="'+item2+'" ng-show="isHideThisTd[sheetF.sheetIndex]['+tdIndex+'].show">' + item2 + '</td>';
                            });
                            tdsHTML += '</tr>';
                            scope.lineNum[scope.sheetF.sheetIndex].push({line: descIndex, show: false});
                            descIndex++;
                        }
                    }
                });

                $timeout(function(){
                    var el = $compile(tdsHTML)(scope);
                    $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody').append(el);

                    if(resp.excel.heads[0] && resp.excel.heads[0]!=="" && resp.excel.heads[1]==="" && resp.excel.heads[1]!=null){

                        if(resp.excel.datas[0]&&resp.excel.datas[1]){
                            scope.mycaptionSelectNum=0;
                            scope.headsAtLineIndex[scope.sheetF.sheetIndex]=0;
                        }
                    }

                },20);


                //$rootScope.$broadcast("loading_Start_EV");
                /*if (scope.sheetF.sheetIndex != 0) {
                    $rootScope.$broadcast("loading_Start_EV");
                }*/


                $timeout(function () {
                   // var el = $compile(tdsHTML)(scope);
                    //$("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody').append(el);
                    $("#fileUpMySheet td .checkbox").checkbox({
                        onChecked: function () {
                            var index = this.getAttribute('index');//从1开始的
                            scope.lineNum[scope.sheetF.sheetIndex][index - 1].show = true;
                            $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr').eq(index - 1).addClass("throline");
                         //   console.log(index);
                        },
                        onUnchecked: function () {
                            var index = this.getAttribute('index');
                            scope.lineNum[scope.sheetF.sheetIndex][index - 1].show = false;
                            $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr').eq(index - 1).removeClass("throline");
                          //  console.log(index);
                        }
                    });


                    $("#fileUpMySheet .ui.tab").height(document.documentElement.clientHeight * 0.88-200);
                    $("#fileUpMySheet .ui.tab #mySheetBox").height(document.documentElement.clientHeight * 0.88-270);
                    $("#fileUpMySheet .ui.tab #mySheetBox").css({
                        "maxHeight":document.documentElement.clientHeight * 0.88-270
                    });
                   // console.log("height:"+$("#fileUpMySheet .ui.tab").height());
                    //$rootScope.$broadcast("loading_End_EV");
                    if(scope.sheetF.sheetIndex != 0){
                        $rootScope.$broadcast("loading_End_EV");
                        scope.myTimer = true;
                    }else{
                        $rootScope.$broadcast("DataIsApeendED");
                    }
                }, 1000);
            }

//sheet Filter
            scope.sheetF = {
                sheetIndex: 0,
                sheetName: "",
                json: {}
            };

            //收到-开始获取
            scope.$on("sheetFilter_EV", function (e,fileName,key) {
                
                $("#fileUpMySheet .ui.tab").each(function(){
                    if($(this).find(".ui.button.red").html()=="上传成功"){
                        console.log('init');
                        $(this).find(".ui.button.call").show();
                        $(this).find(".ui.button.red").removeAttr("disabled").html("上传");
                    }
                });
                if(key ==$rootScope.key) {
                    $rootScope.key = Math.floor(Math.random()*10000000);
                    scope.sheetF = {
                        sheetIndex: 0,
                        sheetName: "",
                        json: {}
                    };
                    scope.myTimer = false;
                    scope.sheetHasNoData = false;
                    tools.post({
                        url: "/Ibm-Client/getSheets.htm",
                        data: {"fileName": fileName},
                        succ: function (resp) {
                            if (resp.success) {
                                scope.mysheet = {};
                                scope.mysheet.sheetNames = resp.value.sheetNames;

                                scope.sheetF.sheetName = resp.value.sheetNames[0];
                                
                                scope.sheetF.json.fileName = fileName;

                                //字段的行位置
                                scope.headsAtLineIndex = [];


                                scope.lineNum = [];//行号
                                scope.sheetDataTypes = [];//表头类型数据
                                scope.sheetDataType = [];//表头类型数据选中的默认值
                                scope.sheetHeads = [];//表的首个字段数据
                                scope.isHideThisTd = [];

                                //初始化
                                for (var i in scope.mysheet.sheeNames) {
                                    //用于删除的行
                                    scope.lineNum.push({});

                                    //tab sheet data
                                    scope.sheetDataTypes.push({});

                                    //sheet headData type
                                    scope.sheetDataType.push({});

                                    //sheet heads
                                    scope.sheetHeads.push({});

                                    //首个字段Atindex
                                    scope.headsAtLineIndex.push({});

                                    scope.isHideThisTd.push([]);
                                }
                                $timeout(function(){
                                    $("#fileUpMySheet .ui.tab").height(document.documentElement.clientHeight * 0.88-200);
                                },10);
                                if (resp.value == null || resp.value.excel == null || resp.value.excel.heads == null || $.isEmptyObject(resp.value.excel.heads)) {
                                    scope.sheetHasNoData = true;
                                    $timeout(function(){
                                        $rootScope.$broadcast("loading_End_EV");
                                    },10);
                                }
                                else {

                                    appendToTable(resp.value);
                                }
                                //appendToTable(resp.value);

                            } else {
//                                alert(resp.message);
                                $timeout(function(){
                                    $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                    return;
                                },500);
                            }
                        }
                    });
                }
                console.log("getfile");

            });


//Tab
            scope.chooseTab = function (index) {
                scope.sheetHasNoData=false;

                scope.mycaptionSelectNum = -1;
//              console.log(scope.sheetF.json.fileContent);
                scope.sheetF.sheetIndex = index;
                scope.sheetF.sheetName = scope.mysheet.sheetNames[index];
                if (scope.sheetHeads[index] == null) {
                    $rootScope.$broadcast("loading_Start_EV");
                    tools.get({
                        type: "POST",
                        url: "/Ibm-Client/getSheets.htm",
                        data: {
                            sheetIndex: index,
                            fileName: scope.sheetF.json.fileName
                        },
                        succ: function (resp) {
                            if (resp.success) {
                                if(resp.value==null||resp.value.excel==null||resp.value.excel.heads==null|| $.isEmptyObject(resp.value.excel.heads)){
                                    scope.sheetHasNoData=true;
                                    $rootScope.$broadcast("loading_End_EV");
                                }
                                else{
                                    appendToTable(resp.value);
                                }

                            } else {
//                                alert(resp.message);
                                $timeout(function(){
                                    $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                    return;
                                },500);
                            }
                        }
                    });
                }
            };

            scope.inputCli = function () {
                console.log(scope.sheetLineNum[0]);
            };

            // scope.headLineNum = 0;
            scope.mycaptionSelectNum = -1;
            scope.mycaptionS = function (index) {
                /* event.stopPropagation();
                 event.preventDefault();*/
//              console.log(event.target.nodeName);


                if (event.target.nodeName != "TD" && event.target.nodeName != "TH") {
                    return;
                }

                if (scope.mycaptionSelectNum == index) {
                    console.log(scope.mycaptionSelectNum+" "+index);
                    console.log("重复");
                   // console.log(scope.mycaptionSelectNum);
                    return
                }
                $rootScope.$broadcast("loading_Start_EV");
                if (index != -1 && scope.lineNum[scope.sheetF.sheetIndex][index].show) {

                    scope.lineNum[scope.sheetF.sheetIndex][index].show = false;
                    $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr').eq(index).removeClass("throline");
                    $timeout(function () {
                        $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr').eq(index).find("input").click();
                    }, 10);

                }

                scope.headsAtLineIndex[scope.sheetF.sheetIndex] = index;
              //  console.log(scope.headsAtLineIndex[scope.sheetF.sheetIndex]);


                var trObjs = $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr');

                if (index == -1) {
                    $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find("#mySheetTable thead th:last").addClass("active");
                    //scope.headsAtLineIndex[scope.sheetF.sheetIndex] = -1;
                    //console.log(trObjs.find(".active"));
                    $("#fileUpMySheet .myBoxsheet").eq(scope.sheetF.sheetIndex).find('#mySheetTable tbody tr.active').removeClass("active");
                } else {

                    trObjs.eq(index).addClass("active").siblings(".active").removeClass("active");
                }

                console.log("index " + index);

                tools.get({
                    type: 'POST',
                    url: "/Ibm-Client/getSheetDataTypes.htm",
                    data: {
                        fileName: scope.sheetF.json.fileName,
                        sheetIndex: scope.sheetF.sheetIndex,
                        fromIndex: index + 2,
                        excludeLineIndexs: ''
                    },
                    succ: function (resp) {
                        if (resp.success) {

                            //表的数据类型重新更新获取
                            scope.sheetDataTypes[scope.sheetF.sheetIndex] = resp.value;

                            var dataTypes = [];
                            angular.forEach(resp.value, function (item, index) {
                                dataTypes.push({show: true});
                               // console.log(item);
                                if ($.isEmptyObject(item)) {
                                    dataTypes[index].show = false;
                                }
                                for (var i in item) {
                                   // console.log(i);
                                    dataTypes[index].type = item[i];
                                    dataTypes[index].str = i;
                                    return;
                                }
                            });
                            //dataType put
                            scope.sheetDataType[scope.sheetF.sheetIndex] = dataTypes;//存放数字
//                    scope.$apply();
                            $timeout(function () {
                                scope.sheetDataType[scope.sheetF.sheetIndex] = dataTypes;
                            }, 10);

                          //  console.log("dataTypes");
                          //  console.log(scope.sheetDataType[scope.sheetF.sheetIndex]);
                            scope.mycaptionSelectNum = index;
                            $rootScope.$broadcast("loading_End_EV");
                        } else {
//                            alert(resp.message);
                            $rootScope.$broadcast("loading_End_EV");
                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","数据修改异常，请找管理员联系。");
                                return;
                            },500);
                        }
                    }
                });
            };


            /* $rootScope.$on("showMySheet_EV",function(){
             $timeout(function(){$("#mySheetBan").show();},10);
             });*/
            scope.cancelUp = function () {
                $rootScope.$broadcast("loading_End_EV");
                $("#fileUpMySheet").modal("hide");

               /* for (var i in scope.mysheet.sheetNames) {
                    $("#fileUpMySheet .myBoxsheet").eq(i).find('#mySheetTable tbody').html("");
                }*/
                /*scope.sheetF = {
                    sheetIndex: 0,
                    sheetName: "",
                    json: {}
                };*/
            };


            //上传

            scope.okUp = function () {

             //   console.log(scope.headsAtLineIndex);
                $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.red").html("上传中..");
                $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.red").attr("disabled",true);

                var tds = "";
                angular.forEach(scope.lineNum[scope.sheetF.sheetIndex], function (item) {
                   // console.log(item);
                    if (item.show) {
                        tds += Number(item.line) + ",";
                    }
                });
                var dataTypes = "";
                angular.forEach(scope.sheetDataType[scope.sheetF.sheetIndex], function (item, index) {
                    if (item.show) {
                        dataTypes += index + '=' + item.str + ",";
                    }
                });

               // console.log(scope.sheetDataType[scope.sheetF.sheetIndex]);
                var json = {
                    tableDesc: scope.sheetF.sheetName,
                    fileName: scope.sheetF.json.fileName,
                    sheetIndex: scope.sheetF.sheetIndex,
                    headLineNum: scope.headsAtLineIndex[scope.sheetF.sheetIndex] + 1,
                    fromIndex: scope.headsAtLineIndex[scope.sheetF.sheetIndex] + 2,
                    excludeLineIndexs: tds,
                    dataTypes: dataTypes
                };
              //  console.log(json);


                tools.post({
                    type: "POST",
                    url: "/Ibm-Client/importSheetDatas.htm",
                    data: {
                        tableDesc: scope.sheetF.sheetName,
                        fileName: scope.sheetF.json.fileName,
                        sheetIndex: scope.sheetF.sheetIndex,
                        headLineNum: scope.headsAtLineIndex[scope.sheetF.sheetIndex] + 1,
                        fromIndex: scope.headsAtLineIndex[scope.sheetF.sheetIndex] + 2,
                        excludeLineIndexs: tds,
                        dataTypes: dataTypes

                    },
                    succ: function (resp) {
                        if (resp.success) {
                           // console.log(resp.value);

                            $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.red").html("上传成功");
                            $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.call").hide();

                            $rootScope.$broadcast("UpdateSliderTable_EV", "File");
                            if(scope.mysheet.sheetNames.length==1){
                                //$("#mySheetTable tbody").html("");
                                $(element).modal("hide");
                                $rootScope.$broadcast("MESSAGE_EV","上传成功");
                            }

                        } else {
                            $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.red").removeAttr("disabled").html("上传失败");
                            $timeout(function(){
                                $("#fileUpMySheet .ui.tab").eq(scope.sheetF.sheetIndex).find(".ui.button.red").removeAttr("disabled").html("上传");
                            },2000);

                            $timeout(function(){
                                $rootScope.$broadcast("MESSAGE_EV","上传失败");
                                return;
                            },500);
                        }
                    }
                });
            };
        }
    }
}]);
